import {createRouter, createWebHashHistory} from 'vue-router'
import home from "../views/home.vue";
import about from "../views/about.vue";
import adminEbook from "../views/admin/admin-ebook.vue";
import adminCategory from "../views/admin/admin-category.vue";
import adminDoc from "../views/admin/admin-doc.vue";
import ebook from "../views/ebook.vue";
import adminUser from "../views/admin/admin-user.vue";
import store from "../store/index.js";

const routes = [
    {path: "/", name: "/", component: home},
    {
        path: "/admin/user",
        name: "adminUser",
        component: adminUser,
        meta: {
            // 需要判断登录
            requiresLogin: true
        }
    },
    {
        path: "/admin/ebook",
        name: "AdminEbook",
        component: adminEbook,
        meta: {
            // 需要判断登录
            requiresLogin: true
        }
    },
    {
        path: "/admin/category",
        name: "adminCategory",
        component: adminCategory,
        meta: {
            // 需要判断登录
            requiresLogin: true
        }
    },
    {
        path: "/admin/doc",
        name: "adminDoc",
        component: adminDoc,
        meta: {
            // 需要判断登录
            requiresLogin: true
        }
    },
    {
        path: "/ebook/:id",
        name: "ebook",
        component: ebook
    },
    {
        path: "/about",
        component: about
    }
]

// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置，但我们在这里
// 暂时保持简单
const router = createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    history: createWebHashHistory(),
    routes, // `routes: routes` 的缩写
})

// 路由守卫
router.beforeEach((to, from, next) => {
    // 而不是去检查每条路由记录
    if (to.matched.some(record => record.meta.requiresLogin)){
        const user = store.state.user;
        // const user = SessionStorage.get("LOGIN_USER");
        // 需要登录
        if (JSON.stringify(user) == "{}"){
            next("/")
        }
    }
    next();

})

export default router;